package cn.melonlib.authentication.comp.service;

import cn.melonlib.authentication.comp.bean.ProfileManager;
import cn.melonlib.authentication.model.entity.Profile;
import cn.melonlib.cache.anno.CacheClass;
import cn.melonlib.cache.anno.CacheMethod;
import cn.melonlib.cache.enums.CacheType;
import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.identification.comp.messenger.IdentificationMessenger;
import cn.melonlib.cores.identification.comp.messenger.OrganizationManager;
import cn.melonlib.cores.identification.model.entity.Identification;
import cn.melonlib.cores.identification.model.entity.Organization;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@ConditionalOnProperty(value = "security.auth.mode",havingValue = "cookie",matchIfMissing = false)
@CacheClass
public class CookieAuthMessenger extends WorkerBasicService<Profile> implements IdentificationMessenger {

    @Resource
    @Lazy
    private ProfileManager profileManager;

    @Resource
    @Lazy
    private OrganizationManager<String> tenantManager;

    public Profile getProfile(){
        try {
            return profileManager.getProfile();
        }catch (Exception e){
            return null;
        }
    }

    @Override
    @CacheMethod(name = "IDENTIFICATION",type = CacheType.REQUEST)
    public Identification getIdentification() {
        return getProfile();
    }

    @CacheMethod(name = "ORGANIZATION",type = CacheType.REQUEST)
    public Organization getOrganization() {
        return tenantManager.getOrganization();
    }

    @Override
    public String getToken() {
        return getProfile().getToken();
    }


}
